package com.sacodemel.financeiro.util;

import com.sacodemel.financeiro.mb.SegurancaMB;
import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class FiltroDeSeguranca implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        
        HttpServletRequest rq = (HttpServletRequest) request;
        HttpServletResponse rp = (HttpServletResponse) response;
        String perfil = (String) rq.getSession().getAttribute("perfil");
        boolean auth =  perfil != null;

        if (!auth && !rq.getRequestURL().toString().contains("login")) {
            
            rp.sendRedirect(rq.getContextPath() + "/paginas/login.xhtml");
            
        } else {

            try {
                
                this.verificaPagina(perfil, rq.getRequestURL().toString());
                chain.doFilter(request, response);
           } catch (SegurancaException e) {
                  rp.sendRedirect(rq.getContextPath() + "/paginas/falha_autorizacao.xhtml");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void destroy() {
    }

    public void init(FilterConfig config) throws ServletException {
    }

    private void verificaPagina(String perfil, String url) throws SegurancaException {
        
        if ( url.contains("Form") && !SegurancaMB.ADM.equals(perfil) ) {
            throw  new SegurancaException("falha_autorizacao");
        }        
        
    }
}